package com.lenovo.newsapp.activity;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.adobe.mobile.Analytics;
import com.adobe.mobile.Config;
import com.lenovo.newsapp.R;
import com.lenovo.newsapp.model.ImageDetail;
import com.lenovo.newsapp.util.Const;
import com.lenovo.newsapp.util.Tools;
import com.lenovo.newsapp.view.MyPopUpWindow;
import com.worklight.wlclient.api.WLClient;
import com.worklight.wlclient.api.WLFailResponse;
import com.worklight.wlclient.api.WLProcedureInvocationData;
import com.worklight.wlclient.api.WLRequestOptions;
import com.worklight.wlclient.api.WLResponse;
import com.worklight.wlclient.api.WLResponseListener;

public class HomeNewsDetailActivity extends Activity implements OnClickListener {

	private static final String TAG = HomeNewsDetailActivity.class
			.getSimpleName();

	private static final String STATUS = "status_code";
	private static final String RESULT = "result";
	private static int statusCode;

	private final Handler handler = new Handler();

	private ArrayList<ImageDetail> imgList;
	private Bitmap bitmap;
	private Dialog dialog;

	private InputMethodManager imm;

	private LinearLayout layoutLoadingBg;
	private RelativeLayout layoutHomeNewsImg;
	private RelativeLayout detailMainRL;
	private RelativeLayout commentBoxRL;
	// private RelativeLayout shareRL;
	private TextView titleTV;
	private TextView authorTV;
	private TextView timeTV;
	private ImageView imgIV;
	private TextView contentTV;
	private TextView imgMarkTV;
	private TextView backBtnTV;
	private TextView moreBtnTV;
	private TextView commentBtnTV;
	private TextView commentListBtnTV;
	private TextView shareCancelBtnTV;
	private EditText commentBoxET;
	private Button commentBoxYesBtn;
	private Button commentBoxNoBtn;

	private String id;
	private String title;
	private String author;
	private String time;
	private String content;
	private String img;
	private String commentStr;

	private MyPopUpWindow popUpWindowMore;
	private MyPopUpWindow popUpWindowShare;

	protected TextView shareBtn;

	protected TextView collectBtn;

	protected TextView paiseBtn;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_detail_home_news);

		layoutHomeNewsImg = (RelativeLayout) findViewById(R.id.home_news_img_rl);
		layoutHomeNewsImg.setOnClickListener(this);

//		backBtnTV = (TextView) findViewById(R.id.white_bar_back_btn_tv);
//		backBtnTV.setOnClickListener(this);

		commentBtnTV = (TextView) findViewById(R.id.bottom_column_grey_comment_btn_tv);
		commentBtnTV.setOnClickListener(this);

		commentBoxYesBtn = (Button) findViewById(R.id.comment_box_btn_yes);
		commentBoxYesBtn.setOnClickListener(this);

		commentBoxNoBtn = (Button) findViewById(R.id.comment_box_btn_no);
		commentBoxNoBtn.setOnClickListener(this);

		moreBtnTV = (TextView) findViewById(R.id.bottom_column_grey_more_btn_tv);
		moreBtnTV.setOnClickListener(this);

		//commentListBtnTV = (TextView) findViewById(R.id.white_bar_comment_list_btn_tv);
		// commentListBtnTV.setOnClickListener(this);

		// shareRL = (RelativeLayout) findViewById(R.id.share_layout_rl);

		// shareCancelBtnTV = (TextView) findViewById(R.id.share_cancel_btn_tv);
		// shareCancelBtnTV.setOnClickListener(this);

		layoutLoadingBg = (LinearLayout) findViewById(R.id.loading_layout);
		//commentBoxRL = (RelativeLayout) findViewById(R.id.comment_box_rl);
		titleTV = (TextView) findViewById(R.id.home_news_title_tv);
		authorTV = (TextView) findViewById(R.id.home_news_author_tv);
		timeTV = (TextView) findViewById(R.id.home_news_time_tv);
		imgIV = (ImageView) findViewById(R.id.home_news_img_iv);
		contentTV = (TextView) findViewById(R.id.home_news_content_tv);
		imgMarkTV = (TextView) findViewById(R.id.home_new_img_mark_tv);
		commentBoxET = (EditText) findViewById(R.id.comment_box_content_et);

		imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

		detailMainRL = (RelativeLayout) findViewById(R.id.home_news_detail_main_rl);
		detailMainRL.getViewTreeObserver().addOnGlobalLayoutListener(
				new OnGlobalLayoutListener() {
					@Override
					public void onGlobalLayout() {

						int heightDiff = detailMainRL.getRootView().getHeight()
								- detailMainRL.getHeight();
						Log.v(TAG, "detailMainRL.getRootView().getHeight() = "
								+ detailMainRL.getRootView().getHeight());
						Log.v(TAG,
								"detailMainRL.getHeight() = "
										+ detailMainRL.getHeight());

						if (heightDiff > 100) { // 说明键盘是弹出状态
							Log.v(TAG, "键盘弹出状态");
							commentBoxRL.setVisibility(View.VISIBLE);
						} else {
							Log.v(TAG, "键盘收起状态");
							commentBoxRL.setVisibility(View.GONE);
						}
					}
				});

		id = getIntent().getStringExtra("id");
		Log.v(TAG, "" + id);
		layoutLoadingBg.setVisibility(View.VISIBLE);
		loadData();
		
		Analytics.trackState("HomeNewsDetailActivity", null);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		Config.pauseCollectingLifecycleData();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		Config.collectLifecycleData();
	}

	public void loadData() {
		Log.v(TAG, "loadData-");

		String adapterName = "NewsAppAdapter";
		String procedureName = "getNewsDetail";

		WLProcedureInvocationData invocationData = new WLProcedureInvocationData(
				adapterName, procedureName);

		// Object[] parameters = new Object[] {"297"};
		Object[] parameters = new Object[] { "" + id };
		invocationData.setParameters(parameters);

		WLRequestOptions options = new WLRequestOptions();
		options.setTimeout(15000);

		LoginActivity.client = WLClient.getInstance();
		LoginActivity.client.invokeProcedure(invocationData,
				new WLResponseListener() {

					public void onSuccess(WLResponse response) {
						Log.v(TAG, "onSuccess-responseText=");
						final JSONObject jsonObj = response.getResponseJSON();
						Log.v(TAG, "onSuccess-dataJson = " + jsonObj);

						try {
							statusCode = jsonObj.getInt(STATUS);
							if (statusCode == 0) {
								JSONObject result = jsonObj
										.getJSONObject(RESULT);
								Log.v(TAG, result.getString("title"));
								title = result.getString("title");
								author = result.getString("author");
								time = result.getString("last_update_time");
								content = result.getString("content");
								//ceshi
								 img = result.getString("title_icon_url");

								JSONArray imgArray = result
										.getJSONArray("news_attachment");
								imgList = new ArrayList<ImageDetail>();
								for (int i = 0; i < imgArray.length(); i++) {
									JSONObject r = imgArray.getJSONObject(i);
									ImageDetail img = new ImageDetail();
									img.setNews_id(r.getInt("news_id"));
									img.setDescription(r
											.getString("description"));
									img.setType(r.getString("type"));
									img.setUrl(r.getString("url"));
									imgList.add(img);

								}
								img = imgList.get(0).getUrl();
								Log.v(TAG, "url = " + Const.DOMAIN + img);
								bitmap = Tools.getBitMap(Const.DOMAIN + img);

							}
						} catch (Exception e) {
							e.printStackTrace();
						}
						handler.post(new Runnable() {
							@Override
							public void run() {
								layoutLoadingBg.setVisibility(View.GONE);
								titleTV.setText(title);
								authorTV.setText(author);
								timeTV.setText(time);
								contentTV.setText(content);
								imgIV.setImageBitmap(bitmap);
								if (imgList != null) {

									if (imgList.size() > 1) {
										imgMarkTV.setVisibility(0);
									}
								}
							}
						});

					}

					public void onFailure(WLFailResponse response) {
						Log.v(TAG, "onFailure-responseText=");
						String responseText = response.getResponseText();
						Log.v(TAG, "onFailure-responseText=" + responseText);
					}

				}, null);
	}

	private void initMoreWindow(View v) {
		if (popUpWindowMore == null) {
			popUpWindowMore = new MyPopUpWindow(this, R.layout.dtail_more, 1) {

				@Override
				public void doLogic(View view) {
					shareBtn = (TextView) view
							.findViewById(R.id.dtail_btn_share);
					shareBtn.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							popUpWindowMore.dismiss();
							dialog = new Dialog(HomeNewsDetailActivity.this,
									R.style.MyShareDialog);
							dialog.setContentView(R.layout.share_layout);
							Window dialogWindow = dialog.getWindow();
							dialogWindow.setGravity(Gravity.BOTTOM);

							dialog.show();
							dialog.getWindow().setLayout(
									LayoutParams.MATCH_PARENT,
									LayoutParams.WRAP_CONTENT);
							shareCancelBtnTV = (TextView) dialog.getWindow()
									.findViewById(R.id.share_cancel_btn_tv);
							shareCancelBtnTV
									.setOnClickListener(new OnClickListener() {

										@Override
										public void onClick(View arg0) {
											// TODO Auto-generated method stub
											dialog.dismiss();
										}
									});
						}
					});

					collectBtn = (TextView) view
							.findViewById(R.id.dtail_btn_collect);
					collectBtn.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View arg0) {
							popUpWindowMore.dismiss();
							Toast.makeText(HomeNewsDetailActivity.this, "收藏成功",
									Toast.LENGTH_SHORT).show();
						}
					});

					paiseBtn = (TextView) view
							.findViewById(R.id.dtail_btn_praise);
					paiseBtn.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View arg0) {
							popUpWindowMore.dismiss();
							Toast.makeText(HomeNewsDetailActivity.this, "点赞成功",
									Toast.LENGTH_SHORT).show();
						}
					});
				}
			};
		}

		int[] location = new int[2];
		v.getLocationOnScreen(location);
		Log.v(TAG, "location[0] = " + location[0]);
		Log.v(TAG, "location[1] = " + location[1]);
		Log.v(TAG, "popupWindow.getHeight() = " + popUpWindowMore.getHeight());
		Log.v(TAG, "v.getWidth() = " + v.getWidth());

		popUpWindowMore.showAtLocation(v, Gravity.BOTTOM, 300, 100);
	}

	// private void initShareWindow() {
	// if (popUpWindowShare == null) {
	// popUpWindowShare = new MyPopUpWindow(this, R.layout.share, 2) {
	//
	// @Override
	// public void doLogic(View view) {
	// // LinearLayout popLayout = (LinearLayout)
	// // view.findViewById(R.id.d);
	//
	// }
	// };
	// }
	//
	// popUpWindowShare.showAtLocation(
	// this.findViewById(R.id.dtail_btn_send), Gravity.BOTTOM, 0, 0);
	// }

	@Override
	public void onClick(View v) {
		int id = v.getId();
		if (id == R.id.white_bar_back_btn_tv) {
			finish();
		} else if (id == R.id.home_news_img_rl) {
			if (imgList.size() > 1) {
				Log.v(TAG, "点击进入图集");
				Intent intent = new Intent(HomeNewsDetailActivity.this,
						NewsDetailImgActivity.class);
				// intent.putExtra("id", new_id);
				startActivity(intent);
			}
		} else if (id == R.id.bottom_column_grey_comment_btn_tv) {
			Log.v(TAG, "弹出输入框");
			Log.v(TAG, "弹出输入框" + commentBoxRL);

			commentBoxRL.setVisibility(View.VISIBLE);
			imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
		} else if (id == R.id.comment_box_btn_yes) {
			commentBoxRL.setVisibility(View.GONE);
			imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
			commentStr = commentBoxET.getText().toString();
			Log.v(TAG, commentStr);
			commentBoxET.setText("");
		} else if (id == R.id.comment_box_btn_no) {
			commentBoxRL.setVisibility(View.GONE);
			imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
			commentBoxET.setText("");
		} else if (id == R.id.white_bar_comment_list_btn_tv) {
			if (commentListBtnTV.getText().toString().equals("0")) {
				Toast.makeText(HomeNewsDetailActivity.this, "暂无评论",
						Toast.LENGTH_SHORT).show();
			} else {
				Intent intent = new Intent(HomeNewsDetailActivity.this,
						CommentListActivity.class);
				// intent.putExtra("id", new_id);
				startActivity(intent);
			}
		} else if (id == R.id.share_cancel_btn_tv) {
			dialog.dismiss();
			// shareRL.setVisibility(View.GONE);
		} else if (id == R.id.bottom_column_grey_more_btn_tv) {
			initMoreWindow(moreBtnTV);
		} else {
		}
	}

}
